/*
 * @(#)IndexBackgroundThreadPool.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.dms.core;

import java.util.LinkedList;

/**
 * Java Thread Queue
 * 
 * This is a thread queue that for Java, 
 * 
 * This is the main class for the thread queue. You should create an instance of
 * this class and assign tasks to it.
 * 
 * For more information visit 
 * http://www-106.ibm.com/developerworks/java/library/j-jtp0730.html
 * 
 * @author Ryan Kwan
 * @version 1.0
 * @deprecated This class has deprecated.
 */
public class IndexBackgroundWorkQueue {
    private final int nThreads;

    private final PoolWorker[] threads;

    private final LinkedList queue;

    private static IndexBackgroundWorkQueue instance=null;
    
    public static synchronized IndexBackgroundWorkQueue getInstance(){
        if(instance==null){
            instance=new IndexBackgroundWorkQueue(20);
        }
        return instance;
    } 
    
    public IndexBackgroundWorkQueue(int nThreads) {
        this.nThreads = nThreads;
        queue = new LinkedList();
        threads = new PoolWorker[nThreads];

        for (int i = 0; i < nThreads; i++) {
            threads[i] = new PoolWorker();
            threads[i].start();
        }
    }

    public void execute(Runnable r) {
        synchronized (queue) {
            queue.addLast(r);
            queue.notify();
        }
    }

    private class PoolWorker extends Thread {
        public void run() {
            Runnable r;

            while (true) {
                synchronized (queue) {
                    while (queue.isEmpty()) {
                        try {
                            queue.wait();
                        } catch (InterruptedException ignored) {
                        }
                    }

                    r = (Runnable) queue.removeFirst();
                }

                // If we don't catch RuntimeException,
                // the pool could leak threads
                try {
                    r.run();
                } catch (RuntimeException e) {
                    // You might want to log something here
                }
            }
        }
    }

}